package me.helllp.bootman.back.config.shiro;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

import me.helllp.bootman.back.logic.system.web.UserController;
import me.helllp.bootman.common.base.BaseReturn;
import me.helllp.bootman.common.base.ErrorCodeEnum;
import me.helllp.bootman.common.utils.ResultUtil;

/**
 * JWT的过滤器
 * 
 * @author Administrator
 *
 */
public class JwtAuthcFilter extends AccessControlFilter {
	
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);
	
	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		//	如果请求方法是options则放行
    	if(org.springframework.http.HttpMethod.OPTIONS.name().equals(getHttpMethod(request))){
    		return true;
    	}
    	
		return false;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) {
		
    	String jwt = WebUtils.toHttp(request).getHeader(org.springframework.http.HttpHeaders.AUTHORIZATION);
    	
    	if(StringUtils.isNotBlank(jwt)){
    		AuthenticationToken token = new JwtToken(jwt, request.getRemoteHost());
    		
    		Subject subject = getSubject(request, response);
    		
    		try {
    			subject.login(token);	
			} catch (AuthenticationException e) {
				responseResult(WebUtils.toHttp(response),ResultUtil.genResultByEnums(ErrorCodeEnum.SYS_UNAUTHORIZED, e.getMessage()));
				return false;
			}
    	}
    	
        return true;
	}

    private void responseResult(HttpServletResponse response, BaseReturn result) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.setStatus(200);
        try {
            response.getWriter().write(JSON.toJSONString(result));
        } catch (IOException ex) {
            logger.error(ex.getMessage());
        }
    } 
    
	/**
	 * 获取请求的方法名
	 * 
	 * @param request
	 * @return
	 */
	private String getHttpMethod(ServletRequest request){
		return WebUtils.toHttp(request).getMethod();
	}
}
